package com.qf.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.qf.entity.ResultEntity;
import com.qf.entity.User;
import com.qf.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping(value = "/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;


    @RequestMapping("/getUserByUsername")
    public User getUserByUsername(String username) {

        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("username", username);
        User user = userService.selectOne(entityWrapper);
        return user;
    }


    @RequestMapping("/checkUser")
    public User checkUser(@RequestBody Map<String, Object> map) {

        EntityWrapper entityWrapper = new EntityWrapper();

        Set<Map.Entry<String, Object>> entries = map.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            entityWrapper.eq(entry.getKey(), entry.getValue());
        }
        User user = userService.selectOne(entityWrapper);

        log.info("user:"+user);
        return user;
    }

    @RequestMapping(value = "/login")
    public ResultEntity login(String username, String password) {

        // 1.设置条件
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("username", username);
        entityWrapper.eq("password", password);

        // 2.查询
        User user = userService.selectOne(entityWrapper);

        if (user != null) {
            return ResultEntity.response(user);
        } else {
            return ResultEntity.error("用户名获密码错误。。。。");
        }
    }

    @RequestMapping(value = "/getUserPage")
    public ResultEntity getUserPage(@RequestBody Page<User> page) {
        return ResultEntity.response(userService.selectPage(page));
    }

    @RequestMapping(value = "/addUser")
    public ResultEntity addUser(@RequestBody User user) {
        return ResultEntity.response(userService.insert(user));
    }


    @RequestMapping(value = "/deleteUser/{id}")
    public ResultEntity deleteUser(@PathVariable Integer id) {
        return ResultEntity.response(userService.deleteById(id));
    }

    @RequestMapping("/updatePassowrd")
    void updatePassowrd(String pw,Integer id){
        User user = new User();
        user.setId(id);
        user.setPassword(pw);
        userService.updateById(user);
    }


}
